
const Controller = require('./base_controller')

class FactorGroupController extends Controller {
  constructor (...props) {
    super(...props)
    this.rule = {
      name: 'string', 
      comment: 'string'
    }
  }
  //查询
  async index (ctx) {
    let { userId } = ctx.params
    try {
      let serveList = await ctx.service.factorGroupService.index(userId)
      this.success({data: serveList.rows})
    } catch (e) {
      this.error({
        msg: '查询失败!',
        data: e
      })
    }
  }
  //创建
  async create (ctx) {
    let { body } = ctx.request
    try {
      ctx.validate(this.rule)
      await ctx.service.factorGroupService.create(body)
      this.success({
        msg: '创建成功!',
        data: body
      })
    } catch (e) {
      let msg = (e && e.invalid_param) 
        ? '参数错误!' : '创建失败,请稍后再试!'
      this.error({
        msg: msg,
        data: e
      })
    }
  }
  //修改
  async update (ctx) {
    let { params, request } = ctx
    try {
      ctx.validate(this.rule)
      let props = Object.assign(params, request.body)
      await ctx.service.factorGroupService.update(props)
      this.success({
        msg: '修改成功!',
        data: props
      })
    } catch (e) {
      let msg = (e && e.invalid_param)
        ? '参数错误!' : '修改失败，请稍后再试!'
      this.error({
        msg: msg,
        data: e
      })
    }
  }
  //删除
  async delete (ctx) {
    let { id } = ctx.params
    try {
      await ctx.service.factorGroupService.delete(id)
      this.success({
        data: { id }
      })
    } catch (e) {
      this.error({
        msg: '删除失败!',
        data: e
      })
    }
  }
  //所有factor名称
  async allFactor (ctx) {
    try {
      let res = await ctx.service.factorGroupService.allFactor()
      this.success({
        data: res.rows
      })
    } catch (e) {
      this.error({
        msg: '查询错误，请稍后再试',
        data: e
      })
    }
  }
  async factorList (ctx) {
    let { id } = ctx.params
    try {
      let res = await ctx.service.factorGroupService.factorList(id)
      this.success({
        data: res.rows
      })
    } catch (e) {
      this.error({
        msg: '查询错误，请稍后再试',
        data: e
      })
    }
  }
  async updateFactorGroup (ctx) {
    let { params, request } = ctx
    try {
      let props = Object.assign(params, request.body)
      await ctx.service.factorGroupService.updateFactorGroup(props)
      this.success()
    } catch (e) {
      this.error({
        msg: '更新失败，请稍后再试！',
        data: e
      })
    }
  }
}

module.exports = FactorGroupController
